package com.ruoyi.framework.websocket;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * WebSocket用户管理
 */
public class WebSocketUsers {
    /**
     * WebSocketUsers 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUsers.class);

    /**
     * 用户集
     */
    private static final Map<String, WebSocketUser> USERS = new ConcurrentHashMap<>();

    /**
     * 添加用户
     */
    public static void put(String sessionId, Session session, Long userId, String userName) {
        WebSocketUser user = new WebSocketUser(session, userId, userName);
        USERS.put(sessionId, user);
    }

    /**
     * 移除用户
     */
    public static boolean remove(String sessionId) {
        WebSocketUser user = USERS.remove(sessionId);
        return user != null;
    }

    /**
     * 获取用户
     */
    public static WebSocketUser get(String sessionId) {
        return USERS.get(sessionId);
    }

    /**
     * 获取用户Session
     */
    public static Session getSession(String sessionId) {
        WebSocketUser user = USERS.get(sessionId);
        return user != null ? user.getSession() : null;
    }

    /**
     * 获取所有用户
     */
    public static Map<String, WebSocketUser> getUsers() {
        return USERS;
    }

    /**
     * 获取在线用户数量
     */
    public static int getOnlineCount() {
        return USERS.size();
    }

    /**
     * 发送消息给指定用户
     */
    public static void sendMessageToUserByText(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            LOGGER.error("\n[发送消息异常]", e);
        }
    }

    /**
     * 发送消息给所有用户
     */
    public static void sendMessageToUsersByText(String message) {
        Collection<WebSocketUser> users = USERS.values();
        for (WebSocketUser user : users) {
            try {
                user.getSession().getBasicRemote().sendText(message);
            } catch (IOException e) {
                LOGGER.error("\n[群发消息异常]", e);
            }
        }
    }

    /**
     * 根据用户ID发送消息
     */
    public static void sendMessageToUserByUserId(Long userId, String message) {
        for (WebSocketUser user : USERS.values()) {
            if (userId.equals(user.getUserId())) {
                sendMessageToUserByText(user.getSession(), message);
                break;
            }
        }
    }

    /**
     * 获取用户信息字符串
     */
    public static String getUserInfo(String sessionId) {
        WebSocketUser user = USERS.get(sessionId);
        if (user != null) {
            return String.format("%s(%s)", user.getUserName(), user.getUserId());
        }
        return "未知用户";
    }
}
